from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.response import Response
import random
from constants import *
from meiduo.utils.ytx_sdk.ytx_sdk.sendSMS import CCP
from celery_tasks.sms.tasks import send_sms_code
from rest_framework import serializers


class SMSCodeView(APIView):
    def get(self,request,mobile):
        """
        1.验证
        2.保存
        3.发送
        :param request:
        :param mobile:
        :return:
        """
        # 获取redis缓存连接
        redis_cli = get_redis_connection('sms_code')

        # 1.验证是否已经发送短信
        sms_flag = redis_cli.get('sms_flag_'+mobile)
        if sms_flag:
            raise serializers.ValidationError('发送验证码太频繁')
            # return Response({'massage':'发送验证码太频繁'})

        # 随机生成一个6位验证码
        code = random.randint(100000,999999)

        # 2.使用管道命令，保存验证码和标识码
        redis_pipeline = redis_cli.pipeline()
        # redis保存命令
        redis_pipeline.setex('sms_code_'+mobile,SMS_CODE_EXPIRES,code)
        redis_pipeline.setex('sms_flag_'+mobile,SMS_FLAG_EXPIRES,1)
        # 执行redis命令
        redis_pipeline.execute()

        # 3.发送验证码
        # print(code)

        sms_code_expires = SMS_CODE_EXPIRES/60
        # CCP.sendTemplateSMS(mobile,sms_code_expires,1)
        sms_code_expires = str(sms_code_expires)
        send_sms_code.delay(mobile,code,sms_code_expires,1)

        return Response({'massage':'OK，发送成功'})
